#include "stdafx.h"
#include "INET_Addr.h"

namespace Network
{
	INET_Addr::INET_Addr (string addr, u_short port)
	{
		memset (&addr_, 0, sizeof addr_);
		addr_.sin_family = AF_INET;
		addr_.sin_port = htons (port);
		addr_.sin_addr.s_addr = inet_addr(addr.c_str());
	}

	INET_Addr::INET_Addr (u_long addr, u_short port)
	{
		memset (&addr_, 0, sizeof addr_);
		addr_.sin_family = AF_INET;
		addr_.sin_port = htons (port);
		addr_.sin_addr.s_addr = htonl (addr);
	}

	INET_Addr::INET_Addr(string address, string port)
	{
		int iResult;
		struct addrinfo hints;
		struct addrinfo* result;
		char* addrChar = new char[address.size() + 1];
		char* portChar = new char[port.size() + 1];

		ZeroMemory(&hints, sizeof(hints));

		hints.ai_family = AF_INET;
		hints.ai_socktype = SOCK_STREAM;
		hints.ai_protocol = IPPROTO_TCP;
		hints.ai_flags = AI_PASSIVE;
		port_ = port;

		// Resolve the server address and port 
		addrChar[address.size()] = 0;
		memcpy(addrChar, address.c_str(), address.size());

		portChar[port.size()] = 0;
		memcpy(portChar, port.c_str(), port.size());

		iResult = getaddrinfo(addrChar, portChar, &hints, &result);
		
		if ( iResult != 0 ) {
			fprintf(stdout, "getaddrinfo failed with error: %d\n", iResult);
		}

		//save result to the addr_ structure
		memset (&addr_, 0, sizeof addr_);
		addr_.sin_family = result->ai_family;
		addr_.sin_port = htons(atoi(portChar)); //convert ASCII to integer -> convert unsigned integer to hostshort
		inet_pton(AF_INET, address.c_str(), &(addr_.sin_addr.s_addr));

		freeaddrinfo(result);
	}

	const sockaddr_in* INET_Addr::Addr () const { return &addr_; }
}